﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;

using Fuse8.DomainFramework.Common.Locator;

using Fuse8.ContentManagementFramework.BizFacade.Services;
using Fuse8.ContentManagementFramework.Domain;

namespace Fuse8.ContentManagementFramework.Web.FormPowered
{
    public class CmsFormPage : Page
    {
        #region Fields

        private CmsPageService _service = new CmsPageService();

        private CmsPage _currentPage;

        private ICmsContext _cmsContext = DependencyServiceLocator.Current.GetInstance<ICmsContext>();

        #endregion

        #region Override event handler

        protected override void OnPreInit(EventArgs e)
        {
            _currentPage = _cmsContext.ContextPage;

            if (_currentPage == null)
            {
                _service.GetPageByUrl("/404");

                _cmsContext.ContextPage = _currentPage;
            }

            BuildControlTree();

            base.OnPreInit(e);
        }

        #endregion

        #region Private methods

        private void BuildControlTree()
        {
            // load the template to use
            CmsTemplate template = _currentPage.Template;

            if (template != null)
            {
                this.MasterPageFile = template.TemplateUrl;

                ContentPlaceHolder placeHolder = null;
                foreach (CmsTemplateRegion templateRegion in template.TemplateRegions)
                {
                    placeHolder = this.Master.FindControl(templateRegion.TemplateRegionName) as ContentPlaceHolder;
                    if (placeHolder != null)
                    {
                        var pageControls = _currentPage[templateRegion];
                        foreach (CmsPageControl pageControl in pageControls)
                        {
                            LoadPageControl(placeHolder, pageControl);
                        }
                    }
                }
            }
        }

        private void LoadPageControl(ContentPlaceHolder placeHolder, CmsPageControl pageControl)
        {
            var control = CmsFormPageControlFactory.LoadControl(pageControl);

            if (control != null)
            {
                placeHolder.Controls.Add(control);
            }
        }

        #endregion
    }
}
